<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="90px">
      <el-form-item label="客户" prop="customerId">
        <matic-select v-model:value="queryParams.customerId" :url="`customer/getAllList/forManager`"
                      @change="queryParams.companyId=''" :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="企业" prop="companyId">
        <matic-select v-model:value="queryParams.companyId"
          :url="`company/getAllList/forManager?${queryParams.customerId ? ('customerId=' + queryParams.customerId) : ''}`"
          :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="电表型号" prop="devicesTypeId">
        <matic-select v-model:value="queryParams.devicesTypeId" :url="`devicesType/getAllList/forManager`"
          :objMap="{ value: 'id', label: 'model' }" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="通讯状态" prop="onlineStatus">
        <matic-select v-model:value="queryParams.onlineStatus" :options="onlineStatus"
          :objMap="{ value: 'value', label: 'label' }" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="电表名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <page-table :url="url.list" ref="table" :tableForm="queryParams" :columns="columns">
      <template #action="scope">
        <el-tooltip content="修改" placement="top">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
        </el-tooltip>
      </template>
      <template #status="scope">
        <el-switch v-model="scope.row.status" v-if="scope.row.status != undefined" :active-value="1" :inactive-value="0"
          @change="handleDelete(scope.row, scope.row.status)"></el-switch>
      </template>
    </page-table>

    <!-- 添加或修改电表配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="客户" prop="customerId">
          <matic-select v-model:value="form.customerId" :url="`customer/getAllList/forManager`"
            :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="企业" prop="companyId">
          <matic-select v-model:value="form.companyId"
            :url="`company/getAllList/forManager?${form.customerId ? ('customerId=' + form.customerId) : ''}`"
            :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="电表型号" prop="devicesTypeId">
          <matic-select v-model:value="form.devicesTypeId" :url="`devicesType/getAllList/forManager`"
            :objMap="{ value: 'id', label: 'model' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="上级电表" prop="parentId">
          <matic-select v-model:value="form.parentId" :url="`devices/getSonList/forManager`"
            :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="电表名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="基本电费计费类型" prop="basePriceType">
          <matic-select v-model:value="form.basePriceType" :options="[
            { value: 0, label: '按容量计费' }, { value: 1, label: '按需量计费' }
          ]" :objMap="{ value: 'value', label: 'label' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="合同-容量值（KVA·月)" prop="capacityLimit">
          <el-input v-model="form.capacityLimit" placeholder="请输入" type="number" min="1" max="100000" />
        </el-form-item>
        <el-form-item label="合同-需量值(kW·月)" prop="demandLimit">
          <el-input v-model="form.demandLimit" placeholder="请输入" type="number" min="1" max="100000"/>
        </el-form-item>
        <el-form-item label="默认用量电价(元/kWh)" prop="electricityPriceYuan">
          <el-input v-model="form.electricityPriceYuan" placeholder="请输入" type="number" min="1" max="100000" />
        </el-form-item>
        <el-form-item label="功率因数标准值" prop="standard">
          <matic-select v-model:value="form.standard" :options="[
            { value: '0.90', label: '0.90' },
            { value: '0.85', label: '0.85' }
          ]" :objMap="{ value: 'value', label: 'label', children: 'children' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="电表编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="安装时间" prop="setupTime">
          <el-date-picker v-model="form.setupTime" style="width:100%" type="date" placeholder="请选择"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from '@/utils/request'
const router = useRouter();
const { proxy } = getCurrentInstance();

const url = ref({
  list: 'devices/getPage/forManager',
  fine: 'devices/getOne/forManager',
  delete: 'devices/disableOrUse/forManager',
  add: 'devices/save/forManager',
  edit: 'devices/save/forManager'
});

const open = ref(false);
const title = ref("");
const table = ref(null);

const columns = ref([
{
  key: 'customer',
  title: '客户',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'company',
  title: '企业',
  ellipsis: true,
  tooltip: true,
},{
  key: 'title',
  title: '电表名称',
  ellipsis: true,
  tooltip: true,
},{
  key: 'basePriceTypeStr',
  title: '基本电费计费类型',
  ellipsis: true,
  tooltip: true,
},{
  key: 'capacityLimit',
  title: '合同-容量值（KVA·月)',
  ellipsis: true,
  tooltip: true,
},{
  key: 'demandLimit',
  title: '合同-需量值(kW·月)',
  ellipsis: true,
  tooltip: true,
},{
  key: 'electricityPriceYuan',
  title: '用量电价(元/kWh)',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'standard',
  title: '功率因数标准值',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'parentDevices',
  title: '上级电表',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'devicesType',
  title: '电表型号',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'onlineStatusStr',
  title: '通信状态',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'sn',
  title: '电表编号',
  ellipsis: true,
  tooltip: true,
}, {
  key: 'remarks',
  title: '备注信息',
  ellipsis: true,
  tooltip: true,
}, {
  key: 'setupTime',
  title: '安装时间',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'createTime',
  title: '创建时间',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'status',
  title: '停用|使用',
  align: 'center',
  width: 80,
  slots: {
    customKey: 'status',
  },
},
{
  title: '操作',
  key: 'action',
  slots: {
    customKey: 'action',
  },
  align: 'center',
  fixed: 'right',
  width: 60
}]);

const handleDelete = (row, status) => {
  const id = row.id
  let text = row.status == "1" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.title + '"吗?').then(function () {
    return request.get(url.value.delete, { params: { id } });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 数据范围选项*/
const onlineStatus = ref([
  { value: 1, label: '在线' }, { value: 2, label: '丢包' }, { value: 3, label: '严重丢包' }, { value: 4, label: '离线' }
]);

const data = reactive({
  form: {},
  queryParams: {},
  rules: {
    title: [{ required: true, message: "电表名称不能为空", trigger: "blur" }],
    sn: [{ required: true, message: "电表编号不能为空", trigger: "blur" }],
    customerId: [{ required: true, message: "客户不能为空", trigger: "blur" }],
    companyId: [{ required: true, message: "企业不能为空", trigger: "blur" }],
    devicesTypeId: [{ required: true, message: "电表型号不能为空", trigger: "blur" }],
    parentId: [{ required: true, message: "上级电表不能为空", trigger: "blur" }],
    setupTime: [{ required: true, message: "安装时间不能为空", trigger: "blur" }],
    basePriceType: [{ required: true, message: "请选择基本电费计费类型", trigger: "blur" }],
    capacityLimit: [{ required: true, message: "合同容量值必须大于等于0", trigger: "blur" }],
    demandLimit: [{ required: true, message: "合同需量值必须大于等于0", trigger: "blur" }],
    electricityPriceYuan: [{ required: true, message: "用量电价必须大于0", trigger: "blur" }],
    standard: [{ required: true, message: "必须选择功率因数标准值", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  table.value.onload();

}
/** 搜索按钮操作 */
function handleQuery() {
  table.value.init();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    title: '',
    model: '',
  };
  proxy.resetForm("roleRef");
}
/** 添加电表 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加电表";
}
/** 修改电表 */
function handleUpdate(row) {
  reset();
  const id = row.id
  request.get(url.value.fine, { params: { id } }).then(({ result }) => {
    form.value = {
      ...result,
      // companyId: String(result.companyId),
      // customerId: String(result.customerId),
      // devicesTypeId: String(result.devicesTypeId),
      // parentId: String(result.parentId),
      // setupTime: result.setupTime,
    };
    open.value = true;
    title.value = "修改电表";
  });
}

/** 提交按钮 */
function submitForm() {
  debugger
  proxy.$refs["roleRef"].validate(valid => {
    debugger
    if (valid) {
      if (form.value.id != undefined) {
        request.post(url.value.edit, form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          location.reload();
        });
      } else {
        request.post(url.value.add, form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          location.reload();
        });
      }

    }

  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


</script>
